<template>
  <a-layout>

    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="部门" prop="OrganizeID">
                <a-tree-select
                  v-model="queryParam.OrganizeID"
                  allowClear
                  :treeData="DepartmentIdTreeData"
                  placeholder="请选择部门"
                  treeDefaultExpandAll
                ></a-tree-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="班次名称">
                <a-select v-model="queryParam.WorkingTimesID" allowClear>
                  <a-select-option v-for="item in WorkingTimesList" :key="item.WorkingTimesID">{{ item.WorkingTimesName }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="选择月份">
                <a-month-picker placeholder="选择月份" v-model="queryParam.YearMonth" @change="onChange" />
              </a-form-item>

            </a-col>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="getDataList">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => (queryParam = {})">重置</a-button>
              <a-button style="margin-left: 8px" type="primary" @click="saveList">保存</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <a-table
        ref="table"
        :columns="columns"
        :rowKey="row => row.WorkingTimesDetailID"
        :dataSource="data"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :bordered="true"
        size="small"
      >
        <span slot="OrganizeID" slot-scope="text, record">
          <template>
            {{ record.OrganizeID | filterOrganize }}
          </template>
        </span>
        <span slot="WorkingTimesID" slot-scope="text, record">
          <a-select v-model="record.WorkingTimesID" allowClear v-if="editable">
            <a-select-option v-for="item in WorkingTimesList" :key="item.WorkingTimesID">{{ item.WorkingTimesName }}</a-select-option>
          </a-select>
          <template v-else>
            {{ record.WorkingTimesID | filterWorkingTimes }}
          </template>
        </span>
        <span slot="Status" slot-scope="text, record">
          <template>
            <a-select v-model.number="record.Status" :default-value="text" style="width: 120px" v-if="editable">
              <a-select-option value="1">
                上班
              </a-select-option>
              <a-select-option value="2">
                休息
              </a-select-option>
              <a-select-option value="3">
                节假日
              </a-select-option>
            </a-select>
            <template v-else>
              {{ text | filterStatus }}
            </template>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="edit(record.WorkingTimesDetailID)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDelete([record.WorkingTimesDetailID])">删除</a>
          </template>
        </span>
      </a-table>

      <edit-form ref="editForm" :row-data="rowData" :afterSubmit="getDataList"></edit-form>
    </a-card>
  </a-layout>
</template>

<script>
import moment from 'moment'
import EditForm from './DetailEditForm'
// eslint-disable-next-line no-unused-vars
let that
const columns = [
  { title: '部门', dataIndex: 'OrganizeID', scopedSlots: { customRender: 'OrganizeID' } },
  { title: '考勤班次', dataIndex: 'WorkingTimesID', scopedSlots: { customRender: 'WorkingTimesID' } },
  { title: '日期', dataIndex: 'WorkingDate' },
  { title: '星期', dataIndex: 'WorkingWeek' },
  { title: '类型', dataIndex: 'Status', width: '200px', scopedSlots: { customRender: 'Status' } },
  { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: '100px' }
]

export default {
  components: {
    EditForm
  },
  props: {
    // eslint-disable-next-line vue/require-default-prop
    rowData: {
      type: Object
    }
  },
  watch: {
    rowData () {
      this.temp = this.rowData
    }
  },
  filters: {
    filterStatus (value) {
      const statusMap = {
        1: '上班',
        2: '休息',
        3: '节假日'
      }
      return statusMap[value]
    },
    filterOrganize (value) {
      var name = ''
      // eslint-disable-next-line no-undef
      const obj = that.findPathByLeafId(value, that.DepartmentIdTreeData)
      name = obj.Text
      return name
    },
    filterWorkingTimes (value) {
      var name = ''
      // eslint-disable-next-line no-undef
      that.WorkingTimesList.forEach(item => {
        if (item.WorkingTimesID === value) {
          name = item.WorkingTimesName
        }
      })
      return name
    }
  },
  mounted () {
    // if (this.rowData.WorkingTimesID !== undefined) {
    //   this.isAddBtn = false
    //   this.queryParam.ParentWorkingTimesDetailID = this.rowData.WorkingTimesID
    //   this.queryParam.ParentWorkingTimesName = this.rowData.WorkingTimesName
    this.init()
    // this.getDataList()
    // }
  },
  beforeCreate: function () {
    that = this
  },
  data () {
    this.dateFormat = 'YYYY-MM-DD'
    return {
      data: [],
      isAddBtn: true,
      temp: this.rowData,
      DepartmentIdTreeData: [],
      WorkingTimesList: [],
      editable: false,
      pagination: {
        current: 1,
        pageSize: 31,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`
      },
      filters: {},
      sorter: { field: 'WorkingTimesDetailID', order: 'asc' },
      loading: false,
      columns,
      queryParam: {},
      visible: false,
      selectedRowKeys: []
    }
  },
  methods: {
    moment,
    onChange (date, dateString) {
      console.log(date, dateString)
    },
    findPathByLeafId (leafId, nodes, path) {
      if (path === undefined) {
        path = {}
      }

      for (var i = 0; i < nodes.length; i++) {
        var tmpPath = path
        //   tmpPath.push(nodes[i].id);
        if (leafId === nodes[i].Id) {
          tmpPath = nodes[i]
          return tmpPath
        }
        if (nodes[i].children) {
          var findResult = this.findPathByLeafId(leafId, nodes[i].children, tmpPath)
          if (findResult) {
            return findResult
          }
        }
      }
    },
    init () {
      this.$http.post('/Base_Manage/Base_Department/GetTreeDataList', {}).then(resJson => {
        if (resJson.Success) {
          this.DepartmentIdTreeData = resJson.Data
        }
      })
      this.$http.post('/Aps/Aps_WorkingTimes/GetDataList', {
        PageIndex: 1,
        PageRows: 200,
        SortField: 'WorkingTimesID',
        SortType: 'asc',
        Search: {},
        ...this.filters }).then(resJson => {
        if (resJson.Success) {
          this.WorkingTimesList = resJson.Data
        }
      })
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }
      this.sorter = { ...sorter }
      this.getDataList()
    },
    edit (key) {
      this.editable = !this.editable
      // debugger
      // const newData = [...this.data]
      // const target = newData.filter(item => key === item.key)[0]
      // this.editingKey = key
      // if (target) {
      //   target.editable = true
      //   this.data = newData
      // }
    },
    getDataList () {
      const _this = this
      this.selectedRowKeys = []
      this.loading = true
      this.queryParam.YearMonth = moment(this.queryParam.YearMonth).format('YYYYMM').substring(0, 6)
      this.$http
        .post('/Aps/APS_OrganizeWorkingTimesDetail/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'WorkingTimesDetailID',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters
        })
        .then(resJson => {
          _this.loading = false
          alert(resJson.Total)
          if (resJson.Total !== undefined && resJson.Total !== 0) {
            _this.editable = false
            _this.data = resJson.Data
            const pagination = { ..._this.pagination }
            pagination.total = resJson.Total
            _this.pagination = pagination
          } else {
            const yearmonth = moment(this.queryParam.YearMonth).format('YYYYMM')
            const year = yearmonth.substring(0, 4)
            const month = yearmonth.substring(4, 6)
            const maxdays = new Date(year, month, 0).getDate()
            // eslint-disable-next-line no-undef
            this.data = []
            for (let i = 1; i <= maxdays; i++) {
              // eslint-disable-next-line no-undef
              const day = year + '-' + month + '-' + i
              var date = moment(new Date(day)).format('YYYY-MM-DD')
              // eslint-disable-next-line no-unused-vars
              const week = moment(new Date(day)).format('dddd')
              this.editable = true
              var model = { WorkingDate: date,
                WorkingTimesDetailID: null,
                Status: '1',
                WorkingWeek: week,
                WorkingTimesID: _this.queryParam.WorkingTimesID,
                OrganizeID: _this.queryParam.OrganizeID
              }
              this.data.push(model)
            }
          }
        })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected () {
      return this.selectedRowKeys.length > 0
    },
    hanldleAdd () {
      this.rowData = this.rowData
      this.$refs.editForm.openForm()
    },
    handleEdit (id) {
      this.rowData = this.rowData
      this.$refs.editForm.openForm(id)
    },
    handleDelete (ids) {
      var thisObj = this
      this.$confirm({
        title: '确认删除吗?',
        onOk () {
          return new Promise((resolve, reject) => {
            thisObj.submitDelete(ids, resolve, reject)
          }).catch(() => console.log('Oops errors!'))
        }
      })
    },
    handleAdd () {
      const { count, dataSource } = this
      const newData = {
        key: count,
        name: `Edward King ${count}`,
        age: 32,
        address: `London, Park Lane no. ${count}`
      }
      this.dataSource = [...dataSource, newData]
      this.count = count + 1
    },
    submitDelete (ids, resolve, reject) {
      this.$http.post('/Aps/APS_OrganizeWorkingTimesDetail/DeleteData', ids).then(resJson => {
        resolve()

        if (resJson.Success) {
          this.$message.success('操作成功!')

          this.getDataList()
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    },
    saveList () {
      const OrganizeWorkingTimes = { WorkingTimesID: this.queryParam.WorkingTimesID, OrganizeID: this.queryParam.OrganizeID, Status: 1 }
      const data = { OrganizeWorkingTimesID: null, OrganizeWorkingTimes: OrganizeWorkingTimes, OrganizeWorkingTimesList: this.data }
      this.$http.post('/Aps/APS_OrganizeWorkingTimesDetail/SaveWorkingTimesData', data).then(resJson => {
        this.confirmLoading = false
        if (resJson.Success) {
          this.$message.success('操作成功!')
          this.afterSubmit()
          this.visible = false
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    }
  }
}
</script>
